<?php

namespace App\Services;

use App\Models\Crm_Product_Package;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;

class ProductService
{
    public function getProductList($params)
    {
        return Crm_Product_Package::getFilter($params)->get();
    }

    public function productList($params)
    {
        $result = Crm_Product_Package::getFilter($params)->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $list['list'] = $result->items();

        return $list;
    }

    public function productStatusUpdate($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Product_Package::find($params['id']);
            $res->status = $params['status'];
            if(!$res->save()){
                throw new \Exception("更新Crm_Product_Package套餐状态失败");
            }
            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function productUpdate($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            if(!empty($params['id'])){
                $res = Crm_Product_Package::where('id',$params['id'])->update([
                    'name' => $params['name'],
                    'price' => $params['price'],
                    'days' => $params['days'],
                    'nums' => $params['nums'],
                    'status' => $params['status'],
                    'remark' => $params['remark']
                ]);
                if(!$res){
                    throw new \Exception("更新Crm_Product_Package套餐失败" );
                }
            }else{
                $res = Crm_Product_Package::create([
                    'agencyid' => $params['aid'],
                    'name' => $params['name'],
                    'price' => $params['price'],
                    'days' => $params['days'],
                    'nums' => $params['nums'],
                    'status' => $params['status'],
                    'remark' => $params['remark']
                ]);
                if(!$res){
                    throw new \Exception("新增Crm_Product_Package套餐失败" );
                }
            }
            DB::commit();
            return true;

        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }
}
